<?php


class Authentification implements Zend_Auth_Adapter_Interface
{
  private $db;
  private $tableName;
  private $nameColumn;
  private $passColumn;

  private $name;
  private $password;

  public function __construct($db)
  {
    $this->db = $db;
    $this->tableName = 'users';
    $this->nameColumn = 'email';
    $this->passColumn = 'password';
  }

  public function setTableName($table)
  {
    $this->tableName = $table;
    return $this;
  }

  public function setIdentityColumn($nameCol)
  {
    $this->nameColumn = $nameCol;
    return $this;
  }

  public function setCredentialColumn($passCol)
  {
    $this->passColumn = $passCol;
    return $this;
  }

  public function setIdentity($name)
  {
    $this->name = $name;
    return $this;
  }

  public function setCredential($pass)
  {
    $this->password = $pass;
    return $this;
  }
  
  public function authenticate()
  {		
	$select = $this->db->select()
               ->from($this->tableName,
          array($this->nameColumn,$this->passColumn))
                ->where($this->nameColumn. ' = ?', $this->name)
                ->where($this->passColumn.' = ?', $this->password);
	
	$this->db->setFetchMode(Zend_Db::FETCH_OBJ);
	$result = $this->db->fetchAll($select);	
	
	$authResult = array(
                   'code' => Zend_Auth_Result::FAILURE,
                   'identity' => $this->name,
                   'messages' => array()			   
                  );
  
    $rows = count($result);
    if($rows == 0)
    {
      $authResult['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
      $authResult['messages'][] = 'Login failed';
    }
    else if($rows > 1)
    {
      $authResult['code'] = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;
      $authResult['messages'][] = 'Login failed';
    }
    else
    {
      $authResult['code'] = Zend_Auth_Result::SUCCESS;
      $authResult['messages'][] = 'Login succesful';
    }
  
    return new Zend_Auth_Result($authResult['code'],$authResult['identity'],
                                $authResult['messages']);
  }
}
?>